package activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codeandmagic.android.gauge.demo.R;
import commons.CheckConnection;
import commons.JSonConvert;

import database.DatabaseUtility;
import database.DeviceProfileDAO;
import database.UserProfileDAO;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class StartScreen extends Activity {
	CheckConnection conCheck;
	private Handler mHandler = new Handler();
	private Runnable mTimer;
	int i = 0;
	boolean resume = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_start_screen);
		// create Database
		DatabaseUtility database = new DatabaseUtility(this);
		database.open();
		database.close();

		// create check connection class
		conCheck = new CheckConnection(this);

		// decrale function to evaluate time loading the screen.
		// if connected to Internet or Loading time > 4 -> change to Main Page
		mTimer = new Runnable() {
			public void run() {
				i++;
				if (conCheck.isConnected() && i == 4) {
					i = 0;
					startActivity(new Intent(StartScreen.this,
							MainActivity.class));
					finish();
				}
				mHandler.postDelayed(this, 1000); // loop it self
			}
		};
		mHandler.postDelayed(mTimer, 0); // start count time
		loadPage();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(mTimer); // remove count time
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (!conCheck.isConnected() && resume == true) {
			resume = true;
			Toast.makeText(getApplicationContext(), "@@", 1000).show();
			i = 0;
			mHandler.postDelayed(mTimer, 0);
			loadPage();
		}
		super.onResume();
	}

	private void loadPage() {
		if (!conCheck.isConnected()) {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setIcon(android.R.drawable.arrow_down_float);
			alert.setTitle("No Connection found");
			alert.setMessage("The system will load your old data, if you want check out new data, please enble your network!");

			alert.setNegativeButton("Enble Wifi", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					startActivityForResult(new Intent(
							Settings.ACTION_WIFI_SETTINGS), 100);
				}
			});
			alert.setNeutralButton("Enble 3G", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					ConnectivityManager dataManager;
					dataManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					Method dataMtd;
					try {
						dataMtd = ConnectivityManager.class.getDeclaredMethod(
								"setMobileDataEnabled", boolean.class);
						dataMtd.setAccessible(true);
						dataMtd.invoke(dataManager, true);
						// wait for 3g enbled.
						Thread.sleep(2000);
						loadPage();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						loadPage();
						Toast.makeText(getApplicationContext(),
								"Oops...Some thing wrong, check again!", 2000)
								.show();
					}

				}
			});
			alert.setPositiveButton("Perform no connection",
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
							startActivity(new Intent(StartScreen.this,
									MainActivity.class));
							finish();
						}
					});
			alert.show();
		} else {
			new SprashScreen("user").execute("http://10.3.9.147:1337/user");
			new SprashScreen("device").execute("http://10.3.9.147:1337/device");
		}
	}

	private class SprashScreen extends AsyncTask<String, Void, String> {
		StringBuilder builder;
		String method;

		public SprashScreen(String method) {
			this.method = method;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... URL) {
			// TODO Auto-generated method stub
			builder = new StringBuilder();
			String line = "";
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(URL[0]);
			try {
				HttpResponse response = client.execute(httpGet);
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					InputStream content = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(content));
					while ((line = reader.readLine()) != null) {
						builder.append(line.toString()).append("\n");

					}
				} else {
					Log.e("Getter", "Failed to download!");
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return new String(builder.toString());
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result.equals("")) {
				Toast.makeText(getApplicationContext(), "Fail to load data..!",
						2000).show();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					Log.d("", "" + e.getMessage());
					e.printStackTrace();
				}
				startActivity(new Intent(StartScreen.this, MainActivity.class));
				finish();
			} else {
				// Log.d("result", result);
				if (method.equals("user")) {
					List<String> list = new ArrayList<String>();
					JSonConvert jConvert = new JSonConvert(StartScreen.this,
							result);
					list = jConvert.getUser();

					UserProfileDAO u = new UserProfileDAO(StartScreen.this);
					u.open();
					for (String temp : list) {
						u.insertProfile(temp, "unknown", "unknown");
					}
					u.close();
				}
				if (method.equals("device")) {
					List<String> list = new ArrayList<String>();
					JSonConvert jConvert = new JSonConvert(StartScreen.this,
							result);
					list = jConvert.getDevice();
					DeviceProfileDAO u = new DeviceProfileDAO(StartScreen.this);
					u.open();
					for (String temp : list) {
						u.insertDevice(temp, "unknown", "unknown", 0,
								"unknown", "unknown");
					}
					u.close();
					startActivity(new Intent(StartScreen.this,
							MainActivity.class));
					finish();
				}
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		int countDiffTime = 0;
		if (requestCode == 100) {
			while (true) {
				if (conCheck.isConnected()) {
					countDiffTime++;
					try {
						Thread.sleep(400);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (countDiffTime == 5)
						break;
					Log.d("", "con: " + conCheck.isConnected());
					loadPage();
					break;
				}
			}
		}

	}
}
